package cn.edu.ctbu.kcsj.webapi;

import cn.edu.ctbu.kcsj.core.PageUtils;
import cn.edu.ctbu.kcsj.domain.Student;
import cn.edu.ctbu.kcsj.service.StudentService;
import cn.edu.ctbu.kcsj.utils.RUtil;
import cn.edu.ctbu.kcsj.vo.R;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

@RestController
@Slf4j
@RequestMapping("/webapi/student")
public class StudentRestController {
    @Autowired
    private StudentService studentService;

    /**
     * 读取的url:webapi/student/list
     * @return
     */
    @GetMapping("/list")
    public R<Page<Student>> list(int page, int size){
        Pageable pageable=PageRequest.of(page,size,Sort.by("sno").descending());
        return RUtil.success(studentService.findAll(pageable));
    }
    @GetMapping("/validateUser")
    public R valideSnoAndPassword(Integer sno,String password) throws Exception{
        return RUtil.success(studentService.validateSnoAndPassword(sno,password));
    }
    /**
     * 分页，读取全部内容
     * @return
     */
    @GetMapping("/getbypage")
    public PageUtils getByPage(@RequestParam(value = "page",defaultValue = "0") Integer page,
                               @RequestParam(value = "size",defaultValue = "10") Integer size,
                               @RequestParam(value = "name",defaultValue = "") String name,
                               @RequestParam(value = "farm",defaultValue = "") String farm){
        Sort sort=Sort.by(Sort.Direction.ASC,"sno");
        Page<Student>studentPage;
        if (StringUtils.isEmpty(name)){
            Pageable pageable=PageRequest.of(page,size,sort);
            studentPage=studentService.findAll(pageable);
        }else if (farm.equals("姓名")&&!StringUtils.isEmpty(name)){
            Student student=new Student();
            student.setSname(name);
            Pageable pageable=PageRequest.of(page,size,sort);
            ExampleMatcher matcher=ExampleMatcher.matching().withMatcher("sname",ExampleMatcher.GenericPropertyMatchers.contains());
            Example<Student>example=Example.of(student,matcher);
            studentPage=studentService.findAll(example,pageable);
        }else{
            Student student=new Student();
            student.setSno(Integer.parseInt(name));
            Pageable pageable=PageRequest.of(page,size,sort);
            ExampleMatcher matcher=ExampleMatcher.matching().withMatcher("sno",ExampleMatcher.GenericPropertyMatchers.contains());
            Example<Student>example=Example.of(student,matcher);
            studentPage=studentService.findAll(example,pageable);
        }


        PageUtils pageUtils=new PageUtils(studentPage.getContent(),studentPage.getTotalElements());
        return pageUtils;
    }
    @GetMapping("/getmy")
    public PageUtils getmy(HttpServletRequest httprequest){
        Page<Student>studentPage;
        Sort sort=Sort.by(Sort.Direction.ASC,"sno");
        HttpSession session=httprequest.getSession();
        Integer sno=(Integer) session.getAttribute("userid");
        Student student=studentService.getBySno(sno);
        student.setSno(student.getSno());
        Pageable pageable=PageRequest.of(0,1,sort);
        ExampleMatcher matcher=ExampleMatcher.matching().withMatcher("sno",ExampleMatcher.GenericPropertyMatchers.contains());
        Example<Student>example=Example.of(student,matcher);
        studentPage=studentService.findAll(example,pageable);
        PageUtils pageUtils=new PageUtils(studentPage.getContent(),studentPage.getTotalElements());
        return pageUtils;
    }
    /**
     * 新增学生方法 /webapi/student/insert
     * @param student
     * @return
     */
    @PostMapping("/insert")
    public R insert(@Valid Student student, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            String errormsg=bindingResult.getFieldError().getDefaultMessage();
            log.info("新增学生时出现错误！{}",errormsg);
            return RUtil.error(-10,errormsg);
        }
        studentService.insert(student);
        return RUtil.success();
    }
    /**
     * 更新学生方法 /webapi/student/update
     * @param student
     * @return
     */
    @PutMapping("/update")
    public Student update(Student student){
        student=studentService.update(student);
        return student;
    }
    /**
     * 删除学生方法 /webapi/student/delete
     * @param sno
     * @return
     */
    @DeleteMapping("/delete/{sno}")
    public void delete(@PathVariable Integer sno){
        studentService.delete(sno);
    }
    @GetMapping("/get/{sno}")
    public Student get(@PathVariable Integer sno){
        Student student=studentService.getBySno(sno);
        return student;
    }
    @GetMapping("/get")
    public String get(HttpServletRequest httprequest){
        HttpSession session=httprequest.getSession();
        Integer sno=(Integer) session.getAttribute("userid");
        Student student=studentService.getBySno(sno);
        String aa=student.getPassword();
        return aa;
    }
    @GetMapping("/getinfo")
    public Student getinfo(HttpServletRequest httprequest){
        HttpSession session=httprequest.getSession();
        Integer sno=(Integer) session.getAttribute("userid");
        Student student=studentService.getBySno(sno);
        return student;
    }
    @RequestMapping ("/logout")
    public int logout(HttpServletRequest httprequest){
        HttpSession session=httprequest.getSession();
        session.setAttribute("userid",null);
        session.setAttribute("user",null);
        return 1;
    }
    @PutMapping("/save/{password}")
    public Integer save(HttpServletRequest httprequest,@PathVariable String password){
        HttpSession session=httprequest.getSession();
        Integer sno=(Integer) session.getAttribute("userid");
        Student student=studentService.getBySno(sno);
        student.setPassword(password);
        studentService.update(student);
        return 1;
    }
}
